package com.qianniu.napi.admin.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.AccountFlow;
import com.qianniu.napi.admin.entity.Jinfo;
import com.qianniu.napi.admin.entity.User;
import com.qianniu.napi.admin.mapper.AccountFlowMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.util.ObjectUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 交易流水表
 * </p>
 *
 * @author chenxuebin
 * @since 2018-07-07
 */
@Controller
public class AccountFlowController {

    private static final Logger logger = LoggerFactory.getLogger(AccountFlowController.class);

    @Autowired
    private IAccountService accountService;
    @Autowired
    private IAccountFlowService accountflowService;
    @Autowired
    private IUserService userService;
    @Autowired
    private AccountFlowMapper accountFlowMapper;

    @Autowired
    private IMaccountService maccountService;
    @Autowired
    private IMaccountFlowService maccountFlowService;

    @RequiresPermissions("admin:user:view")
    @RequestMapping("admin/accountflow/index")
    public String index() {
        return "admin/accountflow";
    }

    @RequiresPermissions("admin:user:view")
    @RequestMapping("/admin/accountflow/list")
    @ResponseBody
    public Page<AccountFlow> alist(@RequestParam(value = "offset", required = false) Integer offset,
                                   @RequestParam(value = "status", required = false) Integer status,
                                   @RequestParam(value = "search", required = false) String search,
                                   @RequestParam(value = "limit", required = false) Integer limit) {
        Wrapper<AccountFlow> wrapper = new EntityWrapper<AccountFlow>();
        int utype = ObjectUtil.getUserType();
        if (utype <= 39)
            wrapper.eq("mpid", ObjectUtil.getMpid());
        else if (utype < 99)
            wrapper.eq("mid", ObjectUtil.getMid());

        wrapper.eq("state", 1);
        if (status != 99) wrapper.eq("xftype", status);
        if (!Strings.isNullOrEmpty(search))
            wrapper.andNew().eq("sn", search).or().eq("nickname", search);

        wrapper.orderBy("id", false);
        Page<AccountFlow> page = accountflowService.selectPage(new Page<AccountFlow>(offset / limit + 1, limit), wrapper);

//        Map map = new HashMap<String,String>();
//        map.put("limit",limit);
//        map.put("offset",offset);
//        int utype = ObjectUtil.getUserType();
//        if (utype < 39) {
//            map.put("mpid", ObjectUtil.getMpid());
//        }else if (utype < 99) {
//            map.put("mid", ObjectUtil.getMid());
//        }
//        if (!Strings.isNullOrEmpty(search)) {
//            map.put("search", search);
//        }
//
//        // 积分账户图像
//        Page<AccountFlow> page = new Page<AccountFlow>(offset / limit + 1, limit);
//        List<AccountFlow> list = accountFlowMapper.getAccountFlowList(map);
//        page.setTotal(accountFlowMapper.getAccountFlowCount(map));
//        page.setRecords(list);
//        page.setSize(list.size());

        return page;
    }

    @RequestMapping("/admin/accountflow/add")
    public String add(@Valid AccountFlow bean, BindingResult bindingResult) {
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            return null;
        }
        bean.setCreatetime(new Date());
        bean.setMid(ObjectUtil.getMid());
        bean.setUid(ObjectUtil.getUid());
        bean.insert();
        return "admin/accountflow";
    }

    @RequestMapping("/admin/accountflow/getAccountFlowById")
    @ResponseBody
    public AccountFlow getAccountFlowById(long id) {
        AccountFlow bean = accountflowService.selectById(id);
        return bean;
    }

    @RequestMapping("/admin/accountflow/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = accountflowService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/accountflow/changeState")
    @ResponseBody
    public String changeState(long id, int state) {
        AccountFlow bean = new AccountFlow();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        accountflowService.updateById(bean);
        return "success";
    }

    @RequestMapping("/admin/accountflow/modify")
    public String update(AccountFlow bean) {
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        boolean isSuccc = accountflowService.updateById(bean);
        if (isSuccc) {
            return "redirect:index";
        }
        return "error";
    }

    @RequestMapping("/test/accountflow/setuinfo")
    @ResponseBody
    public Jinfo setuinfo(String uix) {
        if(Strings.isNullOrEmpty(uix))return null;

        List<AccountFlow> aflist =  accountflowService.selectList(new EntityWrapper<AccountFlow>().eq("mpid",uix));
        List<User> ulist =  userService.selectList(new EntityWrapper<User>().eq("mpid",uix));
        Map<String,User> umap = new HashMap<String,User>();
        for(User item:ulist){
            umap.put("user"+item.getId().toString(),item);
        }
        int skip =0;
        for(AccountFlow item:aflist){
            skip++;
            if(item.getNickname()!=null)continue;
            if(umap.get("user"+item.getUid().toString())==null){
                logger.info("===================================skip="+skip);
                continue;
            }

            item.setNickname(umap.get("user"+item.getUid().toString()).getNickName());
            item.setHeadimg(umap.get("user"+item.getUid().toString()).getAvatarPic());
            item.setPhone(umap.get("user"+item.getUid().toString()).getPhone());
            item.updateAllColumnById();
        }

        return new Jinfo();
    }

}
